//
//  BMPhotoIO_iOS7Tool.m
//  bigmama
//
//  Created by huyuchen on 2017/9/28.
//  Copyright © 2017年 盛成文化. All rights reserved.
//

#import "BMPhotoIO_iOS7Tool.h"

@interface BMPhotoIO_iOS7Tool ()
// ios7相片管理器
@property (nonatomic, strong) ALAssetsLibrary *library;
@end

@implementation BMPhotoIO_iOS7Tool
#pragma mark - 懒加载
- (ALAssetsLibrary *)library
{
    if (!_library) {
        _library = [[ALAssetsLibrary alloc] init];
    }
    return _library;
}

#pragma mark - 授权
// 检查授权
- (void)checkAuthWithAuthedStatus:(void(^)(ALAuthorizationStatus status))authedBlock denied:(void(^)(ALAuthorizationStatus status))deniedBlock
{
    // 取消分享同步
    [ALAssetsLibrary disableSharedPhotoStreamsSupport];
    // 授权
    ALAuthorizationStatus status = [ALAssetsLibrary authorizationStatus];
    if (status == ALAuthorizationStatusDenied || status == ALAuthorizationStatusRestricted) {
        if (deniedBlock) {
            deniedBlock(status);
        }
    } else {
        if (authedBlock) {
            authedBlock(status);
        }
    }
}

#pragma mark - 相片
// 根据相册查询图片
- (void)selectPhotosWithAssetGroup:(ALAssetsGroup *)group finishBlcok:(void (^)(id obj1, id obj2))finishBlock
{
    if (!finishBlock) {
        NSAssert(1 == 2, @"finishBlock不能为空");
    }
    
    BMWeakSelf
    __block NSMutableArray *photosArray = [NSMutableArray array];
    [group enumerateAssetsWithOptions:NSEnumerationConcurrent usingBlock:^(ALAsset *result, NSUInteger index, BOOL *stop) {
        if (result) {
            // 调度会在多个线程，不加锁可能会出现抢夺资源，提前释放的问题
            @synchronized (weakSelf) {
                // 照片模型
                __block BMPhotoIOPhotoModel *model = [weakSelf createPhotoModelWithAsset:result];
                
                // 上一个照片模型
                BMPhotoIOPhotoModel *lastModel = photosArray.lastObject;
                
                // 判断上一个照片模型
                if (lastModel) {
                    // 有值,判断跟当前模型日期是否相同
                    if ([lastModel.createDate yj_isEqualToDateIgnoreTime:model.createDate]) {
                        // 相同日期，直接加入当前组
                        [photosArray addObject:model];
                    } else {
                        // 不同日期，那么要传出旧组，创建新租
                        finishBlock(photosArray, @(NO));
                        photosArray = [NSMutableArray array];
                        [photosArray addObject:model];
                    }
                    
                } else {
                    // 没有值，证明是组的第一个，直接添加到组
                    photosArray = [NSMutableArray array];
                    [photosArray addObject:model];
                }
            }
        } else {
            // 获取完毕
            if (photosArray.count) {
                NSMutableArray *array = [photosArray mutableCopy];
                finishBlock(array, @(YES));
            }
        }
    }];
}

// 创建相片模型对象
- (BMPhotoIOPhotoModel *)createPhotoModelWithAsset:(ALAsset *)result
{
    BMPhotoIOPhotoModel *model = [[BMPhotoIOPhotoModel alloc] init];
    model.createDate = [result valueForProperty:ALAssetPropertyDate];
    model.assetID = [[result valueForProperty:ALAssetPropertyAssetURL] absoluteString];
    model.thumbImage = [[UIImage alloc] initWithCGImage:result.thumbnail];
    model.assetIOS7 = result;
    return model;
}

// 根据asset获取原图
- (UIImage *)originalImageWithAsset:(ALAsset *)asset
{
    ALAssetRepresentation *representation = [asset defaultRepresentation];
    UIImage *originalImage = [UIImage imageWithCGImage:[representation fullResolutionImage] scale:1.0 orientation:(UIImageOrientation)[representation orientation]];
    return originalImage;
}

#pragma mark - 相册
// 查询所有相册
- (void)selectAlbumsWithFinishBlock:(void (^)(id obj))finishBlock
{
    BMWeakSelf
    __block NSMutableArray *albumArray = [NSMutableArray array];
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        [weakSelf.library enumerateGroupsWithTypes:ALAssetsGroupAll usingBlock:^(ALAssetsGroup *group, BOOL *stop) {
            if (group) {
                // 过滤
                [group setAssetsFilter:[ALAssetsFilter allPhotos]];
                if (group.numberOfAssets) {
                    // 相册模型
                    __block BMPhotoIOAlbumModel *album = [weakSelf createAlbumModelWithGroup:group];
                    
                    // 判断是否是相机胶卷
                    NSUInteger type = [[group valueForProperty:ALAssetsGroupPropertyType] integerValue];
                    if (type == ALAssetsGroupSavedPhotos) {
                        [albumArray insertObject:album atIndex:0];
                    } else {
                        [albumArray addObject:album];
                    }
                }
            } else {
                if (albumArray.count) {
                    if (finishBlock) {
                        finishBlock(albumArray);
                    }
                }
            }
        } failureBlock:^(NSError *error) {

        }];
    });
}

- (void)selectVideoAlbumsWithFinishBlock:(void (^)(id obj))finishBlock{
    
    BMWeakSelf
    __block NSMutableArray *albumArray = [NSMutableArray array];
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        [weakSelf.library enumerateGroupsWithTypes:ALAssetsGroupAll usingBlock:^(ALAssetsGroup *group, BOOL *stop) {
            if (group) {
                // 过滤
                [group setAssetsFilter:[ALAssetsFilter allVideos]];
                if (group.numberOfAssets) {
                    // 相册模型
                    __block BMPhotoIOAlbumModel *album = [weakSelf createAlbumModelWithGroup:group];
                    
                    // 判断是否是相机胶卷
                    NSUInteger type = [[group valueForProperty:ALAssetsGroupPropertyType] integerValue];
                    if (type == ALAssetsGroupSavedPhotos) {
                        [albumArray insertObject:album atIndex:0];
                    } else {
                        [albumArray addObject:album];
                    }
                }
            } else {
                if (albumArray.count) {
                    if (finishBlock) {
                        finishBlock(albumArray);
                    }
                }
            }
        } failureBlock:^(NSError *error) {

        }];
    });
}

// 创建相册模型对象
- (BMPhotoIOAlbumModel *)createAlbumModelWithGroup:(ALAssetsGroup *)group
{
    BMPhotoIOAlbumModel *album = [[BMPhotoIOAlbumModel alloc] init];
    // 名称
    album.name = [group valueForProperty:ALAssetsGroupPropertyName];
    album.group = group;
    album.count = group.numberOfAssets;
    album.holderImage = [[UIImage alloc] initWithCGImage:group.posterImage];
    return album;
}

- (void)saveImage:(UIImage *)image metadata:(NSDictionary *)metadata finishedBlock:(void (^)(id obj))finishedBlock
{
    BMWeakSelf
    [self.library writeImageToSavedPhotosAlbum:image.CGImage metadata:metadata completionBlock:^(NSURL *assetURL, NSError *error) {
        if (error) {
            Show_SV_Error_Msg(@"保存图片失败")
            return;
        }
        if (assetURL && finishedBlock) {
            [weakSelf.library assetForURL:assetURL resultBlock:^(ALAsset *asset) {
                finishedBlock(asset);
            } failureBlock:^(NSError *error) {
                Show_SV_Error_Msg(@"保存图片失败")
            }];
        }
    }];
    
}

- (void)selectVideoWithAssetGroup:(ALAssetsGroup *)group finishBlock:(void (^)(id obj1, id obj2))finishBlock{
    if (!finishBlock) {
        NSAssert(1 == 2, @"finishBlock不能为空");
    }
    
    BMWeakSelf
    __block NSMutableArray *videoArr = [NSMutableArray array];
    if ([group numberOfAssets] > 0) {
        [group enumerateAssetsWithOptions:NSEnumerationConcurrent usingBlock:^(ALAsset *result, NSUInteger index, BOOL *stop) {
            if (result) {
                // 调度会在多个线程，不加锁可能会出现抢夺资源，提前释放的问题
                @synchronized (weakSelf) {
                    // 视频模型
                    if ([[result valueForProperty:ALAssetPropertyType] isEqualToString:ALAssetTypeVideo]) {
                        
                        __block BMPhotoIOVideoModel *model = [[BMPhotoIOVideoModel alloc]init];
                        model.createDate = [result valueForProperty:ALAssetPropertyDate];
                        model.assetID = [[result valueForProperty:ALAssetPropertyAssetURL] absoluteString];
                        model.thumbImage = [[UIImage alloc] initWithCGImage:result.thumbnail];
                        model.assetIOS7 = result;
                        model.duration = [[result valueForProperty:ALAssetPropertyDuration]integerValue];
                        
                        // 上一个照片模型
                        BMPhotoIOVideoModel *lastModel = videoArr.lastObject;
                        
                        // 判断上一个照片模型
                        if (lastModel) {
                            // 有值,判断跟当前模型日期是否相同
                            if ([lastModel.createDate yj_isEqualToDateIgnoreTime:model.createDate]) {
                                // 相同日期，直接加入当前组
                                [videoArr addObject:model];
                            } else {
                                // 不同日期，那么要传出旧组，创建新租
                                finishBlock(videoArr, @(NO));
                                videoArr = [NSMutableArray array];
                                [videoArr addObject:model];
                            }
                            
                        } else {
                            // 没有值，证明是组的第一个，直接添加到组
                            videoArr = [NSMutableArray array];
                            [videoArr addObject:model];
                        }
                        
                    }
                }
            } else {
                // 获取完毕
                if (videoArr.count) {
                    NSMutableArray *array = [videoArr mutableCopy];
                    finishBlock(array, @(YES));
                }
            }
            
        }];
    } else {
        // 获取完毕
        if (videoArr.count) {
            NSMutableArray *array = [videoArr mutableCopy];
            finishBlock(array, @(YES));
        }
    }
}


@end
